package pt.isel.pdm.yamba;
import java.util.LinkedList;
import java.util.List;
import winterwell.jtwitter.Twitter;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class TimelinePull extends Service implements Runnable {
	private Thread worker;
	public void onCreate() {
		super.onCreate();
		worker = new Thread(this, "TimelinePull worker thread"); 
		worker.start();
	}
	private void timelinePull(){
		List<Post> elems2 = new LinkedList<Post>();
		List<Twitter.Status> elemstw = Global.getTwitter().getHomeTimeline();
		int nmax = 0;
		int maxmsg = Global.msgskept;
		while((elemstw.size() > 0) && ((nmax++) < maxmsg))
			elems2.add(new Post(elemstw.remove(0)));
		synchronized(Global.elems){
			Global.elems.clear();
			Global.elems.addAll(elems2);
		}
		Log.d("PDM", "Timeline pulled automatically");
		Global.timelineActivity.runOnUiThread(Global.timelineActivity);
	}
	public void run() {
		try {
			while(true){
				try{
					timelinePull();
				}catch(Exception e){
					return;
				}
				synchronized(Global.timelinePullWait){
					if(Global.autotlpull)
						Global.timelinePullWait.wait(Global.pullInterval * 1000);
					else
						Global.timelinePullWait.wait();
				}
			}
		} 
		catch (InterruptedException e){ }
	}
	public int onStartCommand(Intent intent, int flags, int startId) {
		synchronized(Global.timelinePullWait){
			Global.timelinePullWait.notify();
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		worker.interrupt();
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}